<template>
  <div class="app-container">
    <AddBtn :handleClick="handleCreate" :text="text"/>
    <el-table :data="picModelList" border style="width: 100%" v-loading="listLoading">
      <el-table-column align="center" label="ID" prop="id" width="95" type="index"></el-table-column>
      <el-table-column prop="name" label="名称" width="250"></el-table-column>
      <el-table-column prop="isPublic" label="类型">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isPublic=== true" type="primary">公有</el-tag>
          <el-tag v-else type="warning">私有</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="300" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="warning" @click="handleUpdate(scope.$index, scope.row)">
            <i class="el-icon-edit"></i>
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" @click="handleDel(scope.$index, scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
      <el-form label-width="120px" :model="Form" :rules="FormRules" ref="dataForm">
        <el-form-item label="模板名称" prop="name" width="100%">
          <el-input v-model="Form.name"></el-input>
        </el-form-item>
        <el-form-item label="模板类型" prop="isPublic">
          <el-select v-model="Form.isPublic" class="filter-item" placeholder="请选择类型">
            <el-option v-for="item in TypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图片模板" prop="picData">
          <el-upload ref="uploadimg" class="avatar-uploader" :show-file-list="false" :action="uploadAction" :before-upload="beforeAvatarUpload" :on-change="handleChange" :file-list="thisFileList">
            <div class="avatar">
              <img v-if="Form.picData" :src="Form.picData" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" ></i>
            </div>
          </el-upload>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="dialogConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {getPicModelList, getPicModelData, createPicModel, updatePicModel, deletePicModel} from "@/api/pictureModel";
import { getDistributionList } from "@/api/distribution";
import UploadImg from "@/components/Upload/UploadImg";
import AddBtn from "@/views/layout/components/AddBtn";
import { mapGetters } from "vuex";
export default {
  name: "picModelTempDetail",
  props: {
    deviceType: {
      type: Number,
      default: 1
    }
  },
  components: { AddBtn, UploadImg},
  data() {
    return {
      thisFileList:[],
      text: "图片模板",
      picModelList: [],
      listLoading: false,
      dialogStatus: "",
      uploadAction:'http://gsp.coldcloud.com/pictureModel/insert',
      textMap: {
        createIncubator: "新增保温箱图片模板",
        createCar: "新增冷藏车图片模板",
        createWarehouse: "新增库房图片模板",
        updateIncubator: "编辑保温箱图片模板",
        updateCar: "编辑冷藏车图片模板",
        updateWarehouse: "编辑库房图片模板"
      },
      TypeOptions: [{ value: true, label: "公有" }, { value: false, label: "私有" }],
      dialogFormVisible: false,
      formData: new FormData(),
      Form: {
        name: "",
        isPublic: null,
        picData:null,
      },
      FormRules: {
        name: [{ required: true, message: "请输入图片模板名称", trigger: "blur" }],
        isPublic: [{ required: true, message: "请选择类型", trigger: "change" }],
        picData: [{ required: true, message: "请上传模板图片", trigger: "change" }],
      }
    };
  },
  created() {
    this.getList();
  },
  computed: {
    ...mapGetters(["customerid"])
  },

  watch: {
    Form: {
      handler(newval, oldval) {
        //console.log('newval',newval)
        this.Form.picData = newval.picData;
      },
      deep: true,
      immediate: true
    }
  },

  methods: {
     // 上传前检查
    beforeAvatarUpload(file) {
      const isImage = file.type == "image/png" || file.type == "image/jpg" || file.type == "image/jpeg";
      if (!isImage) {
        this.$message.error("上传图片只能是JPG或者png格式!");
      }
      return isImage ;
    },

    handleChange(file,fileList){
      this.thisFileList = fileList.slice(-1);
      console.log(this.thisFileList)
      this.Form.picData = file.url;
      this.formData.set('file', file.raw);
      return false
    },
    
    //获取列表
    getList() {
      this.listLoading = true;
      getPicModelList({ customerId: this.customerid, deviceType: this.deviceType }).then(response => {
          this.picModelList = response.data;
          this.listLoading = false;
        }).catch(e => {});
    },

    // 弹出框确定按钮
    dialogConfirm() {
      if ( (this.dialogStatus === "createIncubator") || (this.dialogStatus === "createCar") || (this.dialogStatus === "createWarehouse") ) {
        this.picModelCreate();
      } else {
        this.picModelUpdate();
      }
    },

    // 新增方案弹窗
    handleCreate() {
      this.Form = {
        name: "",
        isPublic: null,
        picData: null,
      };
      if (this.deviceType === 1) {
        this.dialogStatus = "createIncubator";
      } else if (this.deviceType === 2) {
        this.dialogStatus = "createCar";
      } else {
        this.dialogStatus = "createWarehouse";
      }
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    //新增图片模板
    picModelCreate() {
      this.formData.append('name', this.Form.name)
      this.formData.append('customerId', this.customerid)
      this.formData.append('deviceType', this.deviceType)
      this.formData.append('isPublic',  this.Form.isPublic)
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.$confirm("确认提交吗？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
          }).then(() => {
            createPicModel(this.formData).then(res => {
              this.dialogFormVisible = false;
              this.getList();
              this.$notify({
                title: "成功",
                message: "新增图片模板成功",
                type: "success",
                duration: 2000
              });
              this.$refs.uploadimg.clearFiles();
              this.$refs.dataForm.resetFields();
            }).catch(e=>{console.log(e)});
          }).catch(e=>{console.log(e)});
        }
      });
    },

    //更新弹窗
    handleUpdate(index, row) {
     if (this.deviceType === 1) {
        this.dialogStatus = "updateIncubator";
      } else if (this.deviceType === 2) {
        this.dialogStatus = "updateCar";
      } else {
        this.dialogStatus = "updateWarehouse";
      }
      this.formData= new FormData();
      this.Form.picData = '';
      this.formData.append('id', row.id);
      getPicModelData({ pictureModelId: row.id }).then(res => {
        this.Form = res.data;
        this.Form.picData =res.data.url;
      }).catch(e=>{})
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.dataForm.clearValidate();
      });
    },

    //编辑图片模板
    picModelUpdate() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.formData.append('name', this.Form.name)
          this.formData.append('customerId', this.customerid)
          this.formData.append('deviceType',  this.deviceType)
          this.formData.append('isPublic',  this.Form.isPublic)
          updatePicModel(this.formData).then(() => {
            this.getList();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新图片模板成功",
              type: "success",
              duration: 2000
            });
            this.$refs.uploadimg.clearFiles();
            this.$refs.dataForm.resetFields();
          });
        }
      });
    },

    //删除图片模板
    handleDel(index, row) {
      this.$confirm("确认删除该图片模板吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.listLoading = true;
        deletePicModel({ pictureModelId: row.id }).then(() => {
          this.listLoading = false;
          this.$notify({
            title: "成功",
            message: "删除成功",
            type: "success",
            duration: 2000
          });
          this.getList();
        });
      });
    },

  }
};
</script>
<style lang="scss" scoped>
 .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 158px;
    height: 158px;
    line-height: 158px;
    text-align: center;
  }
  .avatar {
    width: 158px;
    height: 158px;
    display: block;
    border: 1px dashed #d9d9d9;
  }
</style>



